package com.ld.poetry.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ld.poetry.entity.ResourceConfig;
import com.ld.poetry.handle.PoetryRuntimeException;
import com.ld.poetry.service.FileUploadService;
import com.ld.poetry.utils.CommonConst;
import com.ld.poetry.utils.FileUploadUtils;
import com.ld.poetry.vo.FileSizeUnitEnums;
import com.ld.poetry.vo.LocalUploadInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service(CommonConst.UPLOAD_TYPE_KEY_LOCAL)
public class FileUploadLocalServiceImpl implements FileUploadService {
    @Override
    public String upload(MultipartFile file, ResourceConfig config, String key) throws IOException {
        LocalUploadInfo localUploadInfo = JSON.parseObject(config.getInfo(), LocalUploadInfo.class);

        // 上传到本地 检查上传路径
        if(StringUtils.isBlank(localUploadInfo.getUploadPath())){
            throw new PoetryRuntimeException("本地上传路径配置错误！");
        }

        Long maxSizeLong = FileSizeUnitEnums.getMaxSizeLong(localUploadInfo.getUnit(), localUploadInfo.getMaxSize());
        String filePathEnd = FileUploadUtils.upload(localUploadInfo.getUploadPath(), file, maxSizeLong);

        return config.getDownloadUrl() + "/" + filePathEnd;
    }
}
